package com.toman.ui.work.choose;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.toman.Adpter.ItemListAdapter;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.R;
import com.toman.Util.IntentUtils;
import com.toman.Util.KeybordS;
import com.toman.Util.ViewUtil;
import com.toman.toolbar.LoadingEmptyActivity;
import com.toman.widget.MyListView;
import com.toman.Util.ToastUtil;
import com.toman.bean.ItemListBean;
import com.toman.ui.work.base.BeltlineInfActivity;
import com.itheima.pulltorefreshlib.PullToRefreshBase;
import com.itheima.pulltorefreshlib.PullToRefreshScrollView;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.widget.callback.ErrorCallback;
import com.toman.widget.callback.PostUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;


public class ChooseBeltlineEmptyActivity extends LoadingEmptyActivity {

    @BindView(R.id.et_search)
    EditText etSearch;

    @BindView(R.id.mMangeNodata)
    TextView mMangeNodata;
    @BindView(R.id.lv)
    MyListView lv;
    @BindView(R.id.mPullToRefreshScrollView)
    PullToRefreshScrollView mPullToRefreshScrollView;
    ItemListAdapter adapter;
    List<ItemListBean> list = new ArrayList<ItemListBean>();
    int totalPage = 100;
    int page = 2;
    @BindView(R.id.tv_select)
    TextView tvSelect;
    @BindView(R.id.fl_et)
    RelativeLayout flEt;
    private RelativeLayout rlIten1, rlItem2, rlItem3, rlBase;
    private LinearLayout llItem, llSelect;
    private Button btnSearch, btnOk;
    int type = 1;
    MyListView lvItem, lvSelect;
    List<ItemListBean> listItem = new ArrayList<ItemListBean>();
    List<ItemListBean> listSelect = new ArrayList<ItemListBean>();

    ItemListAdapter adapterItem, adapterSelect;

    private ImageView imageCloseOne, imageCloseTwo, imageCloseThree, iv_back, iv_back2, iv_del1, iv_del2, iv_del3;
    private TextView tv_content1, tv_content2, tv_content3, tv_none, tv_none2;
    Dialog dialog;
    String content1 = null, content2 = null, content3 = null;
    EditText et_content1, et_content2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_beltline);

        ButterKnife.bind(this);
        initIntent();
        initView();
        initDialog();
//        initList();
        initLoad();
    }

    @Override
    protected Activity getContent() {
        return ChooseBeltlineEmptyActivity.this;
    }

    @Override
    public void load() {
finish();
    }

//    private void initLoad() {
//        loadService = LoadSir.getDefault().register(this, new Callback.OnReloadListener() {
//            @Override
//            public void onReload(final View v) {
//                // Your can change the status out of Main thread.
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
////                        loadService.showCallback(LoadingCallback.class);
//                        //do retry logic...
//                        switch (v.getId()){
//                            case R.id.btn_retry:
//                                finish();
//                        }
//
//                        //callback
//                    }
//                }).start();
//            }
//        }).setCallBack(EmptyCallback.class, new Transport() {
//            @Override
//            public void order(Context context, View view) {
//                TextView mTvEmpty = (TextView) view.findViewById(R.id.tv_empty);
//                mTvEmpty.setText("您还未添加"+mToolBarHelper.getTvTitle()+"~");
//                Button mButton = (Button) view.findViewById(R.id.btn_retry);
//                TextView tv_toolbar_title = (TextView) view.findViewById(R.id.tv_toolbar_title);
//                tv_toolbar_title.setText(mToolBarHelper.getTvTitle());
//                mButton.setText("点击返回");
//                Toolbar mToolbar=(Toolbar)view.findViewById(R.id.id_tool_bar);
//                mToolbar.setNavigationOnClickListener(new View.OnClickListener()
//                {
//                    @Override
//                    public void onClick(View view)
//                    {
//                        finish();
//                    }
//                });
//                mButton.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        finish();
//                    }
//                });
//            }
//        });
//    }

    private void initIntent() {
        Bundle data = getIntent().getExtras();//获取数据包

        msg = data != null ? data.getString("msg") : null;
        initToolBar(msg);
    }

    private void initView() {
        mPullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        adapter = new ItemListAdapter(this);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemListBean bean = adapter.getItem(i);

                switch (msg) {

                    case "产线信息":
                        Bundle bundle = new Bundle();
                        bundle.putString("id", bean.getID());
                        IntentUtils.startActivity(ChooseBeltlineEmptyActivity.this, BeltlineInfActivity.class, bundle);

                        break;


                }


            }
        });
        customer(1, 1, "");

        mPullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //getHttp(1,1);
                page = 2;
                customer(1, 1, etSearch.getText().toString().trim());


            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                customer(page, 2, etSearch.getText().toString().trim());
                page += 1;


            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                customer(1, 1, s.toString().trim());

            }
        });
    }

    public void initList() {
        tv_none.setVisibility(View.GONE);

        listItem.clear();
        String items[] = new String[]{"正常", "维修", "废弃", "未投产"};

        for (int i = 0; i < items.length; i++) {
            ItemListBean bean = new ItemListBean(items[i], i + "");
            listItem.add(bean);
        }
        adapterItem.refreshData(listItem);
    }

    public void initList2() {
        tv_none2.setVisibility(View.GONE);

        listSelect.clear();
        String items[] = new String[]{"国有企业", "集体企业", "联营企业", "股份合作制企业", "私营企业", "个体户", "合伙企业", "有限责任公司", "股份有限公司", "其它"};

        for (int i = 0; i < items.length; i++) {
            ItemListBean bean = new ItemListBean(items[i], i + "");
            listSelect.add(bean);
        }
        adapterSelect.refreshData(listSelect);
    }

    private void initDialog() {
        adapterItem = new ItemListAdapter(this);
        adapterSelect = new ItemListAdapter(this, 2);
        dialog = new Dialog(this, R.style.BottomDialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        dialog.setContentView(R.layout.dialog_select_belt);
        dialog.setCanceledOnTouchOutside(true); // 外部点击取消
        // 设置宽度为屏宽, 靠近屏幕底部。
        final Window window = dialog.getWindow();
        window.setWindowAnimations(R.style.AnimBottom);
        final WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.BOTTOM; // 紧贴底部
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平
        lp.height = getWindowManager().getDefaultDisplay().getHeight() * 3 / 5;
        window.setAttributes(lp);

        rlIten1 = (RelativeLayout) dialog.findViewById(R.id.re_pay_way);
        rlItem2 = (RelativeLayout) dialog.findViewById(R.id.re_pay_way2);
        rlItem3 = (RelativeLayout) dialog.findViewById(R.id.re_pay_way3);

        rlBase = (RelativeLayout) dialog.findViewById(R.id.re_pay_detail);//付款详情
        llItem = (LinearLayout) dialog.findViewById(R.id.lin_pay_way);//付款方式
        llSelect = (LinearLayout) dialog.findViewById(R.id.ll_select);//付款方式

        lvItem = (MyListView) dialog.findViewById(R.id.lv_bank);//付款方式（银行卡列表）
        lvItem.setAdapter(adapterItem);
        lvSelect = (MyListView) dialog.findViewById(R.id.lv_select);//付款方式（银行卡列表）
        lvSelect.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
        lvSelect.setAdapter(adapterSelect);
        btnSearch = (Button) dialog.findViewById(R.id.btn_search);
        btnOk = (Button) dialog.findViewById(R.id.btn_ok);

        imageCloseOne = (ImageView) dialog.findViewById(R.id.close_one);
        imageCloseTwo = (ImageView) dialog.findViewById(R.id.close_two);
        imageCloseThree = (ImageView) dialog.findViewById(R.id.close_three);

        iv_del1 = (ImageView) dialog.findViewById(R.id.iv_del1);
        iv_del2 = (ImageView) dialog.findViewById(R.id.iv_del2);
        iv_del3 = (ImageView) dialog.findViewById(R.id.iv_del3);

        iv_back = (ImageView) dialog.findViewById(R.id.iv_back);
        iv_back2 = (ImageView) dialog.findViewById(R.id.iv_back2);

        tv_content1 = (TextView) dialog.findViewById(R.id.tv_content1);
        tv_content2 = (TextView) dialog.findViewById(R.id.tv_content2);
        tv_content3 = (TextView) dialog.findViewById(R.id.tv_content3);

        tv_none = (TextView) dialog.findViewById(R.id.tv_none);
        tv_none2 = (TextView) dialog.findViewById(R.id.tv_none2);

        et_content1 = (EditText) dialog.findViewById(R.id.et_content1);
        et_content2 = (EditText) dialog.findViewById(R.id.et_content2);
        rlIten1.setOnClickListener(listener);
        rlItem2.setOnClickListener(listener);
        rlItem3.setOnClickListener(listener);

        btnSearch.setOnClickListener(listener);
        btnOk.setOnClickListener(listener);

        imageCloseOne.setOnClickListener(listener);
        imageCloseTwo.setOnClickListener(listener);
        imageCloseThree.setOnClickListener(listener);

        iv_back.setOnClickListener(listener);
        iv_back2.setOnClickListener(listener);

        iv_del1.setOnClickListener(listener);
        iv_del2.setOnClickListener(listener);
        iv_del3.setOnClickListener(listener);
        lvItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemListBean bean = adapterItem.getItem(i);

                switch (type) {
                    case 1:
                        tv_content1.setText(bean.getName());
                        content1 = bean.getID();
                        iv_del1.setImageResource(R.mipmap.b_shut);
                        break;

                    case 2:
                        tv_content2.setText(bean.getName());
                        content2 = bean.getID();
                        iv_del2.setImageResource(R.mipmap.b_shut);

                        break;

                    case 3:
                        tv_content3.setText(bean.getName());
                        content3 = bean.getID();
                        iv_del3.setImageResource(R.mipmap.b_shut);

                        break;
                }
                rlBase.startAnimation(slide_left_to_left_in);
                rlBase.setVisibility(View.VISIBLE);
                llItem.startAnimation(slide_left_to_right);
                llItem.setVisibility(View.GONE);
            }


        });


    }

    View.OnClickListener listener = new View.OnClickListener() {        @Override        public void onClick(View view) {            KeybordS.hideKeyboard(view);

            switch (view.getId()) {
                case R.id.re_pay_way://选择方式
                    initList();
                    type = 1;
                    rlBase.startAnimation(slide_left_to_left);
                    rlBase.setVisibility(View.GONE);
                    llItem.startAnimation(slide_right_to_left);
                    llItem.setVisibility(View.VISIBLE);
                    break;
                case R.id.re_pay_way2://选择方式
                    getMan();
                    type = 2;
                    rlBase.startAnimation(slide_left_to_left);
                    rlBase.setVisibility(View.GONE);
                    llSelect.startAnimation(slide_right_to_left);
                    llSelect.setVisibility(View.VISIBLE);
                    break;
                case R.id.re_pay_way3://选择方式
                    getMan();
                    type = 3;
                    rlBase.startAnimation(slide_left_to_left);
                    rlBase.setVisibility(View.GONE);
                    llSelect.startAnimation(slide_right_to_left);
                    llSelect.setVisibility(View.VISIBLE);
                    break;
                case R.id.iv_back:

                    rlBase.startAnimation(slide_left_to_left_in);
                    rlBase.setVisibility(View.VISIBLE);
                    llItem.startAnimation(slide_left_to_right);
                    llItem.setVisibility(View.GONE);

                case R.id.iv_back2:
                    rlBase.startAnimation(slide_left_to_left_in);
                    rlBase.setVisibility(View.VISIBLE);
                    llSelect.startAnimation(slide_left_to_right);
                    llSelect.setVisibility(View.GONE);
                    break;
                case R.id.btn_search://确认付款
                    search();
                    break;
                case R.id.btn_ok://确认付款
                    SparseBooleanArray array;
                    array = lvSelect.getCheckedItemPositions();
                    if (array.size() <= 0) {
                        rlBase.startAnimation(slide_left_to_left_in);
                        rlBase.setVisibility(View.VISIBLE);
                        llSelect.startAnimation(slide_left_to_right);
                        llSelect.setVisibility(View.GONE);
                        return;
                    }
                    String name = "";
                    boolean first = true;

                    switch (type) {
                        case 2:
                            content2 = "";
                            for (int i = 0; i < array.size(); i++) {
                                ToastUtil.print(i + "" + array.get(i) + "");
                                if (array.get(i)) {
                                    ItemListBean bean = adapterSelect.getItem(i);
                                    if (first) {
                                        name = bean.getName();
                                        content2 = bean.getID() + "";
                                        first = false;
                                    }
                                    else 
                                    {
                                        name = name + "、" + bean.getName();
                                        content2 = content2 + "," + bean.getID();

                                    }

                                }


                            }
tv_content2.setText(name);
                            iv_del2.setImageResource(R.mipmap.b_shut);

                            break;
                        case 3:
                            content3 = "";

                            for (int i = 0; i < array.size(); i++) {
                                ToastUtil.print(i + "" + array.get(i) + "");
                                if (array.get(i)) {
                                    ItemListBean bean = adapterSelect.getItem(i);
                                    if (first) {
                                        name = bean.getName();
                                        content3 = bean.getID() + "";
                                        first = false;
                                    }
                                    else
                                    {
                                        name = name + "、" + bean.getName();
                                        content3 = content3 + "," + bean.getID();

                                    }

                                }


                            }

                            tv_content3.setText(name);
                            iv_del3.setImageResource(R.mipmap.b_shut);
                            break;

                    }
                    rlBase.startAnimation(slide_left_to_left_in);
                    rlBase.setVisibility(View.VISIBLE);
                    llSelect.startAnimation(slide_left_to_right);
                    llSelect.setVisibility(View.GONE);
                    break;
                case R.id.close_one:
                    dialog.dismiss();
                    break;
                case R.id.close_two:
                    dialog.dismiss();

                case R.id.close_three:
                    dialog.dismiss();
                    break;
                case R.id.iv_del1:
                    content1 = "";
                    tv_content1.setText("请选择");
                    iv_del1.setImageResource(R.mipmap.right);
                    break;
                case R.id.iv_del2:
                    content2 = "";
                    tv_content2.setText("请选择");
                    iv_del2.setImageResource(R.mipmap.right);
                    break;
                case R.id.iv_del3:
                    content3 = "";
                    tv_content3.setText("请选择");
                    iv_del3.setImageResource(R.mipmap.right);
                    break;
                default:
                    break;
            }
        }
    };

    /*
      企业列表
   */
    public void customer(Integer page, final Integer type, String search) {


        OkHttpUtils
                .get(NewBaseUrl.beltline_list_get)
                .params("companyId", companyId)
                .params("departmentIdList", getIntent().getStringExtra("id"))
                .params("token", token)
                .params("key", search)
                .params("limit", NewBaseUrl.num)                .params("page", page.toString())
                .execute(new StringCallback() {
                             @Override
                             public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                                 super.onError(isFromCache, call, response, e);
                                 PostUtil.postCallbackDelayed(loadService, ErrorCallback.class);
                             }

                             @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "产线列表: " + result);
                        if (type == 1) {
                            list.clear();
                        }
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            JSONObject Jpage = jsonObj.getJSONObject("page");
                            totalPage = Jpage.getIntValue("totalPage");
                            JSONArray jsonArray = Jpage.getJSONArray("list");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                ItemListBean bean = new ItemListBean(jsonArray.getJSONObject(i).getString("beltlineName"), jsonArray.getJSONObject(i).getString("id"));
                                list.add(bean);
                            }
                            adapter.refreshData(list);
                          isEmpty(list,mMangeNodata);
                            adapter.notifyDataSetChanged();
                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                        mPullToRefreshScrollView.onRefreshComplete();
                    }

                             public void onError(Call call, Exception e) {


                             }
                }

                );


     }

    public void search() {
        if (dialog!=null){        dialog.dismiss();
        }
        ToastUtil.print("操作工" + content2 + "");

        OkHttpUtils
                .get(NewBaseUrl.beltline_select)
                .params("token", token)
                .params("companyId", companyId)
                .params("departmentId", getIntent().getStringExtra("id"))


                .params("beltlineCode", et_content1.getText().toString())
                .params("beltlineName", et_content2.getText().toString())
                .params("beltlineStatus", content1)
                .params("operatorUserId", content2)
                .params("maintenanceUserId", content3)

                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "产线列表: " + result);

                        list.clear();

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            JSONArray jsonArray = jsonObj.getJSONArray("beltlineEntityList");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                ItemListBean bean = new ItemListBean(jsonArray.getJSONObject(i).getString("beltlineName"), jsonArray.getJSONObject(i).getString("id"));
                                list.add(bean);
                            }
                            adapter.refreshData(list);
                            if (list.size() == 0) {
                                mMangeNodata.setVisibility(View.VISIBLE);
                            } else {
                                mMangeNodata.setVisibility(View.GONE);

                            }
                            adapter.notifyDataSetChanged();
                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    public void getMan() {

        OkHttpUtils
                .get(NewBaseUrl.user_select)
                .params("token", token)
                .params("companyId", companyId)

                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "获取人员列表: " + result);
                        listSelect.clear();
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            JSONArray jsonArray = jsonObj.getJSONArray("sysUserEntityList");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                ItemListBean bean = new ItemListBean(jsonArray.getJSONObject(i).getString("username"), jsonArray.getJSONObject(i).getString("userId"));
                                listSelect.add(bean);
                                lvSelect.setItemChecked(i, false);

                            }
                            if (listSelect.size() == 0) {
                                tv_none2.setVisibility(View.VISIBLE);
                            } else {
                                tv_none2.setVisibility(View.GONE);
                            }
                            adapterSelect.refreshData(listSelect);
                            adapterSelect.notifyDataSetChanged();
                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }


    @OnClick(R.id.tv_select)
    public void onViewClicked() {
        dialog.show();
    }
}
